import React, { useEffect,  useState } from "react";
import {
  Alert,
  Dimensions,
  Image,
  ScrollView,
  Switch,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import styles from "./index.style";
import RowButton from "@/components/Global/CustomButton/RowButton";
import { router } from "expo-router";
import { SessionType } from "@/types/chat-session";
import AlertService from "@/components/Global/Alert/service";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {useChatMessageActions, useChatMessageState} from "@/hooks/chat/chat-message";

interface SessionMemberProps {
  id: string;
  nickname: string;
  avatar: string;
}

const { width } = Dimensions.get("window");
const AVATAR_WIDTH = 60 + 6; // 头像宽度 + margin
const itemsPerRow = Math.floor(width / AVATAR_WIDTH);

export default function ChatSessionInfo() {
  //当前会话成员
  const [sessionMembers, setSessionMembers] = useState<SessionMemberProps[]>([]);
  //当前会话信息
  const { session } = useChatMessageState()
  //免打扰
  const [mute, setMute] = useState(session.disturb);
  const [pinChat, setPinChat] = useState(session.pined);
  //发送通知
  const [reminder, setReminder] = useState(false);
  const { updateSession } = useChatSessionActions()

  // sqlite数据库消息操作
  const {deleteAllMessages}  = useChatMessageActions()

  useEffect(() => {
    if (session.sessionType === SessionType.SINGLE) {
      setSessionMembers([
        {
          id: session.sessionId,
          nickname: session.sessionName,
          avatar: session.sessionAvatar,
        },
      ]);
    }
  }, []);

  const renderAvatarRow = () => {
    const totalMembers = sessionMembers.length;
    const maxVisible =
      totalMembers >= itemsPerRow
        ? Math.floor(itemsPerRow * 3 - 4)
        : totalMembers;
    const newSessionMembers = sessionMembers.slice(0, maxVisible);
    const showMore = sessionMembers.length > maxVisible;

    // 构造渲染列表
    const items = [...newSessionMembers];

    const components = items.map((item, index) => {
      return (
        <View key={item.id} style={styles.avatarContainer}>
          <TouchableOpacity
            onPress={() => router.navigate(`userprofile/${item.id}`)}
          >
            <Image source={{ uri: item.avatar }} style={styles.avatar} />
          </TouchableOpacity>
          <Text style={styles.avatarLabel}>{item.nickname}</Text>
        </View>
      );
    });

    // 判断是否需要另起一行放查看更多按钮
    const isFullRow = components.length % itemsPerRow === 0;

    return (
      <>
        <View style={styles.avatarRow}>
          {components}
          {showMore && isFullRow && <View style={{ width: "100%" }} />}
        </View>
        {showMore && (
          <View style={styles.avatarLastRow}>
            <TouchableOpacity onPress={() => console.log("查看更多")}>
              <Text style={styles.checkMoreMember}>查看更多群成员</Text>
            </TouchableOpacity>
          </View>
        )}
      </>
    );
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.avatarRow}>
        {renderAvatarRow()}
        <TouchableOpacity
          style={styles.addContainer}
          onPress={() => console.log("添加成员")}
        >
          <Ionicons name="add" size={32} color="#ccc" />
        </TouchableOpacity>
      </View>
      <View style={styles.switchContainer}>
        <RowButton
          style={styles.switchItem}
          text={"消息免打扰"}
          tailComponent={
            <Switch
              value={mute}
              onValueChange={async () => {
                setMute(!mute);
                await updateSession({
                  sessionId: session.sessionId,
                  disturb: !mute,
                });
              }}
            />
          }
        />
        <RowButton
          style={styles.switchItem}
          text={"置顶聊天"}
          tailComponent={
            <Switch
              value={pinChat}
              onValueChange={async () => {
                setPinChat(!pinChat);
                await updateSession({
                  sessionId: session.sessionId,
                  pined: !pinChat,
                });
              }}
            />
          }
        />
        <RowButton
          style={styles.switchItem}
          text={"提醒"}
          tailComponent={
            <Switch
              value={reminder}
              onValueChange={async () => {
                setReminder(!reminder);
                await updateSession({
                  sessionId: session.sessionId,
                  notice: !reminder,
                });
              }}
            />
          }
        />
      </View>

      <View style={styles.optionItemContainer}>
        <RowButton
          style={styles.optionItem}
          text={"查找聊天记录"}
          onPress={() => {}}
        />
        <RowButton
          style={styles.optionItem}
          text={"清空聊天记录"}
          onPress={() => {
            Alert.alert("清空聊天记录", "是否清空聊天记录？", [
              { text: "取消", style: "cancel" },
              {
                text: "确定",
                onPress: async () => {
                  await deleteAllMessages(session.sessionId);
                  await updateSession({
                    sessionId: session.sessionId,
                    lastMessage: "",
                    lastMessageId: "",
                    unreadCount: 0,
                  });
                  AlertService.showAlert("success", "聊天记录已清空");
                },
              },
            ]);
          }}
        />
      </View>
    </ScrollView>
  );
}
